package com.voucher.qiege.three;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.*;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;

public class SessionManager {
    // 创建全局CookieStore
    public static final CookieStore cookieStore = new BasicCookieStore();
    // 创建带Cookie支持的HttpClient
    public static final CloseableHttpClient httpClient = HttpClients.custom()
            .setDefaultCookieStore(cookieStore)
            .setRedirectStrategy(new LaxRedirectStrategy()) // 自动处理重定向
            .build();

    // 初始化会话（主入口）
    public static String initSession() throws Exception {
        // 访问登录页触发服务器生成会话
        HttpGet getLoginPage = new HttpGet("http://oa.mexingroup.com:9999/login.jsp");
        try (CloseableHttpResponse response = httpClient.execute(getLoginPage)) {
            // 检查Cookie中是否包含JSESSIONID
            return cookieStore.getCookies().stream()
                    .filter(c -> "JSESSIONID".equals(c.getName()))
                    .findFirst()
                    .map(Cookie::getValue)
                    .orElseThrow(() -> new RuntimeException("无法获取JSESSIONID"));
        }
    }
}
